import { service } from '@/utils/request'

// 设备管理API
export interface Device {
  id: string
  name: string
  status: 'online' | 'offline'
  user_nickname: string
  last_heartbeat: string
  created_at: string
}

export interface DeviceLog {
  id: number
  timestamp: string
  level: string
  message: string
  device_id: string
}

export interface DeviceListParams {
  page: number
  pageSize: number
  keyword?: string
}

export interface DeviceListResponse {
  records: Device[]
  total: number
  page: number
  pageSize: number
}

export interface DeviceLogListParams {
  page: number
  pageSize: number
  deviceId: string
  startTime?: string
  endTime?: string
}

export interface DeviceLogListResponse {
  records: DeviceLog[]
  total: number
  page: number
  pageSize: number
}

/**
 * 获取设备统计数据
 */
export const getDeviceStats = () => {
  return service({
    url: '/devices/statistics',
    method: 'get'
  })
}

/**
 * 获取设备列表
 */
export const getDeviceList = (params: DeviceListParams) => {
  return service<DeviceListResponse>({
    url: '/devices',
    method: 'get',
    params
  })
}

/**\n * 获取设备选项列表（用于下拉框）\n */
export const getDeviceOptions = () => {
  return service<Device[]>({
    url: '/devices',
    method: 'get'
  })
}

/**\n * 获取设备日志\n */
export const getDeviceLogs = (params: DeviceLogListParams) => {
  return service<DeviceLogListResponse>({
    url: `/devices/${params.deviceId}/logs`,
    method: 'get',
    params: {
      page: params.page,
      pageSize: params.pageSize,
      startTime: params.startTime,
      endTime: params.endTime
    }
  })
}

/**
 * 断开设备连接
 */
export const disconnectDevice = (deviceId: string) => {
  return service({
    url: `/devices/${deviceId}/disconnect`,
    method: 'post'
  })
}

/**
 * 获取设备详情
 */
export const getDeviceDetail = (deviceId: string) => {
  return service({
    url: `/devices/${deviceId}/status`,
    method: 'get'
  })
}

/**
 * 发送设备命令
 */
export const sendDeviceCommand = (deviceId: string, command: string, params?: any) => {
  return service({
    url: `/devices/${deviceId}/command`,
    method: 'post',
    data: { command, params }
  })
}

/**
 * 锁定设备
 */
export const lockDevice = (deviceId: string) => {
  return service({
    url: `/devices/${deviceId}/lock`,
    method: 'post'
  })
}

/**
 * 解锁设备
 */
export const unlockDevice = (deviceId: string) => {
  return service({
    url: `/devices/${deviceId}/unlock`,
    method: 'post'
  })
}

/**
 * 设置设备维护状态
 */
export const setDeviceMaintenance = (deviceId: string, maintenance: boolean) => {
  return service({
    url: `/devices/${deviceId}/maintenance`,
    method: 'post',
    data: { maintenance }
  })
}
